<template>
    <el-tabs v-model="activeName" type="card" class="tab-content" @tab-remove="removeTab" @tab-click="tabClick">
      <el-tab-pane
          v-for="(item, index) in tabs"
          :key="index"
          :name="item.name"
          :label="item.label"
          :closable="item.name !== '/welcome'"
      >
        <el-scrollbar :style="{ height: scrollHeight + 'px' }">
          <router-view/>
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>
</template>


<script setup>
import {ref, watch, onMounted, onBeforeUnmount} from 'vue';
import {useRoute, useRouter} from 'vue-router';

const route = useRoute();
const router = useRouter();

const tabs = ref([]);
const activeName = ref(route.path);

//监听路由变化
watch(route, () => {
  console.log("watch,route.path:" + route.path)
  if (route.path === '/login') {
    return;
  }
  //查询tabs中是否已经存在该路由,不存在则添加
  const find = tabs.value.find(item => item.name === route.path);
  if (find == undefined && route.path !== '/') {
    console.log("watch,addTab:" + route.path)
    tabs.value.push({name: route.path, label: route.path.replace('/', '')});
  }
  if (activeName.value !== route.path) {
    activeName.value = route.path;
  }
  console.log("watch,activeName.value:" + activeName.value)
});

//删除tab
const removeTab =(targetName) => {
  console.log("removeTab,targetName:" + targetName)
  tabs.value = tabs.value.filter(item => item.name !== targetName);
  if (tabs.value.length) {
    activeName.value = tabs.value[0].name;
  } else {
    activeName.value = '/';
  }
  console.log("removeTab,activeName:" + activeName.value)
  router.push(activeName.value);
}

//点击tab切换
const tabClick =(tab) => {
  activeName.value = tab.props.name;
  router.push(tab.props.name);
}
const scrollHeight = ref(0);
const setScrollHeight = () => {
  const tabContent = document.querySelector('.tab-content');
  const tabHeader = document.querySelector('.el-tabs__header');
  const headerHeight = document.querySelector('.navbar-containt');
  if (tabContent && tabHeader) {
    console.log("tabContentHeight:" + tabContent.clientHeight + " tabHeaderHeight:" + tabHeader.clientHeight + " headerHeight:" + headerHeight.clientHeight)
    scrollHeight.value = tabContent.clientHeight - tabHeader.clientHeight - headerHeight.clientHeight;
  }
  console.log("scrollHeight:" + scrollHeight.value)
};

onMounted(() => {
  setScrollHeight();
  window.addEventListener('resize', setScrollHeight);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', setScrollHeight);
});

</script>

<style lang="scss">
.tab-content {
  height: calc(100vh - 62px);
  display: flex;
  padding: 10px 0 0 10px;
}

/*修改el-tabs_header样式*/
.tab-content > .el-tabs__header {
  align-items: center;
  display: flex;
  justify-content: space-between;
  margin: 0px;
  padding: 0px;
  position: relative;
}

</style>